package ru.vboxdc.service;

import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;

import java.sql.DriverManager;
import java.sql.Connection;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * User: lelon
 * Date: 28.02.2009
 * Time: 20:15:15
 */
public class InstallDataBase {

    private static Logger logger = Logger.getLogger(InstallDataBase.class);

    public void run() {
        logger.debug("start");
        try {
            Properties props = Resources.getResourceAsProperties("database.properties");
            String url = props.getProperty("url");
            String driver = props.getProperty("driver");
            String username = props.getProperty("username");
            String password = props.getProperty("password");

            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url, username, password);

            try {
                ScriptRunner runner = new ScriptRunner(conn, false, false);
                runner.setErrorLogWriter(null);
                runner.setLogWriter(null);
                runner.runScript(Resources.getResourceAsReader("install-schema.sql"));
                logger.debug("script install-schema.sql done");
                runner.runScript(Resources.getResourceAsReader("install-dataload.sql"));
                logger.debug("script install-dataload.sql done");
            } finally {
                conn.close();
            }

        } catch (Exception e) {
            throw new RuntimeException("Description.  Cause: " + e, e);
        }
        logger.debug("end");
    }
}